package com.jic.veteran.portal.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jic.veteran.common.api.CommonResult;
import com.jic.veteran.common.api.ResultCode;
import com.jic.veteran.model.UmsMember;
import com.jic.veteran.portal.domain.WxAuthParam;
import com.jic.veteran.portal.service.ProjectDonationService;
import com.jic.veteran.portal.service.UmsMemberService;
import com.jic.veteran.portal.util.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@Api(tags = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${wx.wxAppId}")
    private String wxAppId;
    @Value("${wx.wxAppSecret}")
    private String wxAppSecret;
    @Value("${wx.wxAppUrl}")
    private String wxAppUrl;
    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private ProjectDonationService projectDonationService;


    @ApiOperation("小程序授权认证以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestBody WxAuthParam wxAuthParam,
                             @RequestParam(value = "phone", defaultValue = "") Long phone,
                             @RequestParam(value = "password", defaultValue = "") String password) {


        if (phone == null || password == null) {
            return CommonResult.failed(ResultCode.FAILED,"用户名密码不能为空");
        }

        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
       JSONObject jsonObject = WechatUtil.getSessionKeyOrOpenId(wxAuthParam.getCode(),wxAppId,wxAppSecret,wxAppUrl);
//        if (ObjectUtil.isEmpty(jsonObject) || StrUtil.isNotEmpty(jsonObject.getStr("errcode"))) {
//            return CommonResult.failed(ResultCode.FAILED,"调用微信端授权认证接口错误");
//        }
        // 3.接收微信接口服务 获取返回的参数
        String openId = jsonObject.getStr("openid");
        String sessionKey = jsonObject.getStr("session_key");
        String unionId = jsonObject.getStr("unionid");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        /*String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return CommonResult.failed(ResultCode.FAILED, "签名校验失败");
        }*/
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        UmsMember umsMember = umsMemberService.getByPhone(phone);
        Map<String, String> resultMap = new HashMap<>();
        if(ObjectUtil.isEmpty(umsMember)) {
            return CommonResult.failed(ResultCode.FAILED,"用户不存在");
        } else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (!encoder.matches(password, umsMember.getPassword())) {
                return CommonResult.failed(ResultCode.FAILED,"密码不正确");
            }

            //更新登录时间
            umsMember.setSessionKey(sessionKey);
            umsMember.setLoginTime(DateUtil.date());
            if(StrUtil.isNotEmpty(unionId)) {
                umsMember.setUnionId(unionId);
            }
//            umsMember.setAvatarUrl(wxAuthParam.getAvatarUrl());
//            umsMember.setNickName(wxAuthParam.getNickName());
//            umsMemberService.update(umsMember.getOpenId(),umsMember);
            resultMap.put("nickName",umsMember.getNickName());
            resultMap.put("avatarUrl",umsMember.getAvatarUrl());
            resultMap.put("userType",StrUtil.isNotEmpty(umsMember.getUserType()) ? umsMember.getUserType() : "");
            resultMap.put("cname",StrUtil.isNotEmpty(umsMember.getCname()) ? umsMember.getCname() : "");
            resultMap.put("idno",StrUtil.isNotEmpty(umsMember.getIdno()) ? umsMember.getIdno() : "");
            resultMap.put("phone",StrUtil.isNotEmpty(umsMember.getPhone()) ? umsMember.getPhone() : "");
        }
        // 生成token，用于维护微信小程序用户与服务端的会话
        String token = umsMemberService.getToken(umsMember.getUsername(),password);
        if (StrUtil.isEmpty(token)) {
            return CommonResult.failed(ResultCode.FAILED,"生成token错误");
        }
        resultMap.put("token", token);
        resultMap.put("openid", umsMember.getId().toString());

        //6. 返回给小程序数据
        return CommonResult.success(resultMap);
    }


    @ApiOperation("修改验证手机或者密码")
    @RequestMapping(value = "/updatePhonePasswd", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updatePhonePasswd(@RequestParam(value = "id", defaultValue = "") Long id,
                               @RequestParam(value = "phone", defaultValue = "") Long phone,
                               @RequestParam(value = "password", defaultValue = "") String password) {

        Integer a = umsMemberService.updatePhonePasswd(id,phone,password);

        if (a == -1) {
            return CommonResult.failed("该手机号码已被其他人绑定！");
        }

        return CommonResult.success(a);
    }

//    @ApiOperation("小程序授权认证以后返回token")
//    @RequestMapping(value = "/auth", method = RequestMethod.POST)
//    @ResponseBody
//    public CommonResult auth(@RequestBody WxAuthParam wxAuthParam) {
//        // 1.接收小程序发送的code
//        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
//        JSONObject jsonObject = WechatUtil.getSessionKeyOrOpenId(wxAuthParam.getCode(),wxAppId,wxAppSecret,wxAppUrl);
//        if (ObjectUtil.isEmpty(jsonObject) || StrUtil.isNotEmpty(jsonObject.getStr("errcode"))) {
//            return CommonResult.failed(ResultCode.FAILED,"调用微信端授权认证接口错误");
//        }
//        // 3.接收微信接口服务 获取返回的参数
//        String openId = jsonObject.getStr("openid");
//        String sessionKey = jsonObject.getStr("session_key");
//        String unionId = jsonObject.getStr("unionid");
//
//        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        /*String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
//        if (!signature.equals(signature2)) {
//            return CommonResult.failed(ResultCode.FAILED, "签名校验失败");
//        }*/
//        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
//        UmsMember umsMember = umsMemberService.getByUsername(openId);
//        Map<String, String> resultMap = new HashMap<>();
//        if(ObjectUtil.isEmpty(umsMember)) {
////            JSONObject userInfo = WechatUtil.getUserInfo(encrypteData,sessionKey,iv);
//            JSONObject userInfo = JSONUtil.parseObj(wxAuthParam.getRawData());
//            if (ObjectUtil.isEmpty(userInfo)) {
//                return CommonResult.failed(ResultCode.FAILED,"解密用户信息错误");
//            }
//            UmsMember umsMemberNew = JSONUtil.toBean(userInfo,UmsMember.class);
//            if (ObjectUtil.isEmpty(umsMemberNew)) {
//                return CommonResult.failed(ResultCode.FAILED,"填充用户对象错误");
//            }
//            umsMemberNew.setUsername(openId);
//            umsMemberNew.setOpenId(openId);
//            umsMemberNew.setSessionKey(sessionKey);
//            if(StrUtil.isNotEmpty(unionId)) {
//                umsMemberNew.setUnionId(unionId);
//            }
//            umsMemberNew.setAvatarUrl(wxAuthParam.getAvatarUrl());
//            umsMemberNew.setNickName(wxAuthParam.getNickName());
//            umsMemberService.create(umsMemberNew);
//            resultMap.put("nickName",umsMemberNew.getNickName());
//            resultMap.put("avatarUrl",umsMemberNew.getAvatarUrl());
//            //userType,cname,id,phone
//        } else {
//            //更新登录时间
//            umsMember.setSessionKey(sessionKey);
//            umsMember.setLoginTime(DateUtil.date());
//            if(StrUtil.isNotEmpty(unionId)) {
//                umsMember.setUnionId(unionId);
//            }
////            umsMember.setAvatarUrl(wxAuthParam.getAvatarUrl());
////            umsMember.setNickName(wxAuthParam.getNickName());
//            umsMemberService.update(umsMember.getOpenId(),umsMember);
//            resultMap.put("nickName",umsMember.getNickName());
//            resultMap.put("avatarUrl",umsMember.getAvatarUrl());
//            resultMap.put("userType",StrUtil.isNotEmpty(umsMember.getUserType()) ? umsMember.getUserType() : "");
//            resultMap.put("cname",StrUtil.isNotEmpty(umsMember.getCname()) ? umsMember.getCname() : "");
//            resultMap.put("idno",StrUtil.isNotEmpty(umsMember.getIdno()) ? umsMember.getIdno() : "");
//            resultMap.put("phone",StrUtil.isNotEmpty(umsMember.getPhone()) ? umsMember.getPhone() : "");
//        }
//        // 生成token，用于维护微信小程序用户与服务端的会话
//        String token = umsMemberService.getToken(openId,null);
//        if (StrUtil.isEmpty(token)) {
//            return CommonResult.failed(ResultCode.FAILED,"生成token错误");
//        }
//        String totalProject = projectDonationService.getPersonTotalProject(openId);
//        if(StrUtil.isNotEmpty(totalProject)) {
//            resultMap.put("totalProject", totalProject);
//        } else {
//            resultMap.put("totalProject", "0");
//        }
//        String totalDonateAmout = projectDonationService.getPersonTotalDonateAmout(openId);
//        if(StrUtil.isNotEmpty(totalDonateAmout)) {
//            resultMap.put("totalDonateAmout", totalDonateAmout);
//        } else {
//            resultMap.put("totalDonateAmout", "0.00");
//        }
//        resultMap.put("token", token);
//        resultMap.put("openid", openId);
//
//        //6. 返回给小程序数据
//        return CommonResult.success(resultMap);
//    }
//
//    @ApiOperation("获取会员信息")
//    @RequestMapping(value = "/info/{openid}", method = RequestMethod.GET)
//    @ResponseBody
//    public CommonResult info(@PathVariable String openid) {
//        UmsMember member = umsMemberService.getCurrentMember();
//        return CommonResult.success(member);
//    }

//    @ApiOperation("获取验证码")
//    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
//    @ResponseBody
//    public CommonResult getAuthCode(@RequestParam String telephone) {
//        String authCode = umsMemberService.generateAuthCode(telephone);
//        return CommonResult.success(authCode,"获取验证码成功");
//    }


    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);

        String refreshToken = umsMemberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
//    @ApiOperation("小程序维护用户信息")
//    @RequestMapping(value = "/update/{openid}", method = RequestMethod.POST)
//    @ResponseBody
//    public CommonResult update(@PathVariable(value = "openid") String openid, UmsMember umsMember) {
//        umsMemberService.update(openid,umsMember);
//        return CommonResult.success(200,"修改成功");
//    }
}
